<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="角色名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-button v-has-perm="'view:role'" class="filter-item" type="primary" @click="handleFilter">
        查询
      </el-button>
      <el-button v-has-perm="'add:role'" class="filter-item" type="success" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column prop="id" label="ID" align="center" width="80" />
      <el-table-column prop="name" label="角色名称" min-width="150" />
      <el-table-column prop="description" label="角色描述" min-width="200" />
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column label="操作" align="center" width="250">
        <template #default="{ row }">
          <el-button v-has-perm="'edit:role'" size="small" type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-has-perm="'edit:role'" size="small" type="warning" @click="handlePermission(row)">
            权限
          </el-button>
          <el-button v-has-perm="'delete:role'" v-test-account size="small" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total > 0"
      :total="total"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="listQuery.limit"
      v-model:current-page="listQuery.page"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 角色编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form
        ref="dataForm"
        :model="tempRole"
        :rules="rules"
        label-position="left"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="tempRole.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input 
            v-model="tempRole.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入角色描述" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button v-test-account type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog title="权限设置" v-model="permDialogVisible" width="600px">
      <el-tree
        ref="permissionTree"
        :data="permissionTree"
        show-checkbox
        node-key="id"
        :default-checked-keys="defaultPermissions"
        :props="{ label: 'name', children: 'children' }"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permDialogVisible = false">取 消</el-button>
          <el-button v-test-account type="primary" @click="submitPermissions">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRoles, getRole, createRole, updateRole, deleteRole, getRolePermissions, updateRolePermissions } from '@/api/role'
import { getPermissions } from '@/api/permission'

const router = useRouter()
const list = ref([])
const total = ref(0)
const listLoading = ref(false)
const dialogVisible = ref(false)
const permDialogVisible = ref(false)
const dialogTitle = ref('')
const dataForm = ref(null)
const permissionTree = ref([])
const defaultPermissions = ref([])
const currentRoleId = ref(null)
const permissionTreeRef = ref(null)

const listQuery = reactive({
  page: 1,
  limit: 10,
  name: ''
})

const tempRole = reactive({
  id: undefined,
  name: '',
  description: ''
})

const rules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
}

// 获取角色列表
const getList = async () => {
  listLoading.value = true
  try {
    const response = await getRoles()
    list.value = response.data || []
    total.value = list.value.length
  } catch (error) {
    console.error('获取角色列表失败', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    listLoading.value = false
  }
}

// 获取权限树
const getPermissionTree = async () => {
  try {
    const response = await getPermissions()
    // 这里假设后端返回的数据已经是树形结构
    permissionTree.value = response.data || []
  } catch (error) {
    console.error('获取权限列表失败', error)
    ElMessage.error('获取权限列表失败')
  }
}

// 筛选
const handleFilter = () => {
  listQuery.page = 1
  getList()
}

// 每页数量变化
const handleSizeChange = (val) => {
  listQuery.limit = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  listQuery.page = val
  getList()
}

// 创建角色
const handleCreate = () => {
  dialogTitle.value = '创建角色'
  dialogVisible.value = true
  
  // 重置表单
  nextTick(() => {
    if (dataForm.value) {
      dataForm.value.resetFields()
    }
    
    Object.assign(tempRole, {
      id: undefined,
      name: '',
      description: ''
    })
  })
}

// 更新角色
const handleUpdate = async (row) => {
  dialogTitle.value = '编辑角色'
  dialogVisible.value = true
  
  // 获取角色详情
  try {
    const response = await getRole(row.id)
    Object.assign(tempRole, response.data)
  } catch (error) {
    console.error('获取角色详情失败', error)
    ElMessage.error('获取角色详情失败')
  }
}

// 设置权限
const handlePermission = async (row) => {
  currentRoleId.value = row.id
  
  // 获取角色权限和所有权限
  try {
    await getPermissionTree()
    
    const response = await getRolePermissions(row.id)
    defaultPermissions.value = response.data || []
    
    permDialogVisible.value = true
  } catch (error) {
    console.error('获取角色权限失败', error)
    ElMessage.error('获取角色权限失败')
  }
}

// 提交权限
const submitPermissions = async () => {
  if (!currentRoleId.value) return
  
  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
  const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
  
  try {
    await updateRolePermissions(currentRoleId.value, allCheckedKeys)
    ElMessage.success('权限设置成功')
    permDialogVisible.value = false
  } catch (error) {
    console.error('设置权限失败', error)
    ElMessage.error('设置权限失败')
  }
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRole(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除角色失败', error)
      ElMessage.error('删除角色失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!dataForm.value) return
  
  // 表单验证
  try {
    await dataForm.value.validate()
    
    // 是新增还是编辑
    if (tempRole.id === undefined) {
      // 新增
      await createRole(tempRole)
      ElMessage.success('创建成功')
    } else {
      // 编辑
      await updateRole(tempRole.id, tempRole)
      ElMessage.success('更新成功')
    }
    
    // 关闭对话框并刷新列表
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
}

.dialog-footer {
  text-align: right;
}
</style> 